/*
 * Copyright 2002 by Mark A. Kobold
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the License.
 *
 * The Original Code is iSQL-Viewer, A Mutli-Platform Database Tool. 
 *
 * The Initial Developer of the Original Code is Markus A. Kobold.
 * 
 * Portions created by Mark A. Kobold are
 * Copyright (C) Copyright (C) 2000 Mark A. Kobold. All Rights Reserved.
 * Contributor(s): Mark A. Kobold  <mkobold@sprintpcs.com>.
 *
 * Contributor(s): all the names of the contributors are added in the source code
 * where applicable.
 *
 * If you didn't download this code from the following link, you should check if
 * you aren't using an obsolete version:
 * http://isql.sourceforge.net/
 */
package org.isqlviewer.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.isqlviewer.util.LocalMessages;

/**
 * Modal dialog to prompt the user for variable substitution.
 * <p>
 * 
 * @author Mark A. Kobold &lt;mkobold at isqlviewer dot com&gt;
 * @version 1.0
 */
public class VariableSubstitutor extends JDialog implements ActionListener {

    private static final long serialVersionUID = 8720304755017125400L;
    private static final Insets INSETS = new Insets(2, 2, 2, 2);
    private static final GridBagConstraints UI_CONSTRAINT = new GridBagConstraints(0, 0, 0, 0, 0, 0, 0, 0, INSETS, 0, 0);

    private static final String BUNDLE_IDENTIFIER = "org.isqlviewer.ui.ResourceBundle";
    private static final LocalMessages messages = new LocalMessages(BUNDLE_IDENTIFIER);

    private DefaultComboBoxModel selectionModel = new DefaultComboBoxModel();
    private JComboBox previousSelections = new JComboBox(selectionModel);
    private JButton okButton = new JButton(messages.getMessage("VariableSubstitutor.okbutton"));
    private JButton cancelButton = new JButton(messages.getMessage("VariableSubstitutor.cancelbutton"));
    private String substitution = null;

    public VariableSubstitutor(Frame frameParent, String variableName, Preferences preferences) {

        super(frameParent, messages.format("VariableSubstitutor.title", variableName), true);
        try {
            String[] selectionValues = preferences.keys();
            for (int i = 0; i < selectionValues.length; i++) {
                selectionModel.addElement(selectionValues[i]);
            }
        } catch (BackingStoreException e) {
        }
        initializeUI(variableName);
    }

    public String getSubstitution() {

        return substitution;
    }

    public void actionPerformed(ActionEvent e) {

        Object src = e.getSource();
        if (src instanceof JTextField || src.equals(okButton)) {
            JTextField field = (JTextField) previousSelections.getEditor().getEditorComponent();
            substitution = field.getText();
            dispose();
        } else if (src.equals(cancelButton)) {
            substitution = null;
            dispose();
        }
    }

    @Override
    protected void processWindowEvent(WindowEvent e) {

        switch (e.getID()) {
            case WindowEvent.WINDOW_OPENED :
                previousSelections.requestFocus();
                setLocationRelativeTo(getOwner());
                break;
        }
        super.processWindowEvent(e);
    }

    private void initializeUI(String variableName) {

        Component component = null;
        Object constraint = null;

        JPanel contentPanel = new JPanel(new GridBagLayout());

        component = new JLabel(variableName);
        ((JLabel) component).setLabelFor(previousSelections);
        constraint = constrain(0, 1, 1, 1, 0.0d, 0.0d, GridBagConstraints.WEST, GridBagConstraints.NONE);
        contentPanel.add(component, constraint);

        previousSelections.setEditable(true);
        previousSelections.setMaximumRowCount(5);
        previousSelections.setRequestFocusEnabled(true);
        ((JTextField) previousSelections.getEditor().getEditorComponent()).addActionListener(this);
        component = previousSelections;
        constraint = constrain(1, 1, 1, 1, 1.0d, 0.0d, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
        contentPanel.add(component, constraint);

        component = Box.createVerticalStrut(10);
        constraint = constrain(0, 2, 2, 1, 0.0d, 0.0d, GridBagConstraints.WEST, GridBagConstraints.NONE);
        contentPanel.add(component, constraint);

        JComponent commandPanel = new JPanel(new GridBagLayout());
        JButton actionButton = null;

        constraint = constrain(0, 0, 1, 1, 1.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
        commandPanel.add(Box.createHorizontalStrut(10), constraint);

        constraint = constrain(1, 0, 1, 1, 1.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
        commandPanel.add(Box.createHorizontalGlue(), constraint);

        actionButton = okButton;
        actionButton.addActionListener(this);
        actionButton.setActionCommand(Integer.toString(0));
        actionButton.setToolTipText(messages.getMessage("VariableSubstitutor.okbutton.tip"));
        constraint = constrain(2, 0, 1, 1, 0.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.NONE);
        commandPanel.add(actionButton, constraint);

        actionButton = cancelButton;
        actionButton.addActionListener(this);
        actionButton.setActionCommand(Integer.toString(1));
        actionButton.setToolTipText(messages.getMessage("VariableSubstitutor.cancelbutton.tip"));
        constraint = constrain(3, 0, 1, 1, 0.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.NONE);
        commandPanel.add(actionButton, constraint);

        constraint = constrain(4, 0, 1, 1, 0.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
        commandPanel.add(Box.createHorizontalStrut(10), constraint);

        constraint = constrain(0, 1, 5, 1, 0.0d, 0.0d, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
        commandPanel.add(Box.createVerticalStrut(10), constraint);

        getRootPane().setDefaultButton(okButton);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Container container = new JPanel(new BorderLayout());
        container.add(contentPanel, BorderLayout.CENTER);
        container.add(commandPanel, BorderLayout.SOUTH);
        container.add(Box.createVerticalStrut(10), BorderLayout.NORTH);
        container.add(Box.createHorizontalStrut(10), BorderLayout.WEST);
        container.add(Box.createHorizontalStrut(10), BorderLayout.EAST);

        setContentPane(container);
        setResizable(false);
        pack();
    }

    private static GridBagConstraints constrain(int x, int y, int w, int h, double wx, double wy, int a, int f) {

        UI_CONSTRAINT.gridx = x;
        UI_CONSTRAINT.gridy = y;
        UI_CONSTRAINT.gridwidth = w;
        UI_CONSTRAINT.gridheight = h;
        UI_CONSTRAINT.weightx = wx;
        UI_CONSTRAINT.weighty = wy;
        UI_CONSTRAINT.anchor = a;
        UI_CONSTRAINT.fill = f;
        return UI_CONSTRAINT;
    }
}